package my.example.samplegridview;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.util.Vector;

import my.example.samplegridview.modal.user;
import o2s.utils.imageHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class menu extends Activity {
	
	AssetManager _assetManager;
	menu _self;
	public static int requestCode = 100;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.menu);
		_assetManager = getAssets();
		_self = this;
		staticVar.menuStatic = this;
		
		Intent i = getIntent();
		if(currentuserdetail.currentuser.getUseremail().compareTo("guest") == 0){
			LinearLayout ll = (LinearLayout) findViewById(R.id.menuuserlayer);
			ll.setVisibility(View.GONE);
		}
		else{
			LinearLayout ll = (LinearLayout)findViewById(R.id.menuuserlayer);
			ll.setVisibility(View.VISIBLE);
			
			ImageView iv = (ImageView)findViewById(R.id.menuCustomerImage);
			Bitmap bm = imageHelper.getImageFromResource(staticVar.menuStatic, currentuserdetail.currentuser.getUserImage());
			iv.setImageBitmap(bm);
		}
		
		// Switch User Button 
		Button switchuserbutton = (Button)findViewById(R.id.menuswitchuser);
		switchuserbutton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				
				final Dialog dialog = new Dialog(_self);
				dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
				dialog.setContentView(R.layout.loginprompt);
				
				//Set Up GuestButton
				Button guestLogin = (Button)dialog.findViewById(R.id.loginpromptguestlogin);
				guestLogin.setVisibility(View.VISIBLE);
				guestLogin.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View arg0) {
						currentuserdetail.currentuser = currentuserdetail.temporaryUserLookup("guest", "");
						LinearLayout ll = (LinearLayout)staticVar.menuStatic.findViewById(R.id.menuuserlayer);
						ll.setVisibility(View.GONE);
						Toast.makeText(_self, "Welcome "+currentuserdetail.currentuser.getUseremail()+" ! You can now start ordering foods.", Toast.LENGTH_SHORT).show();
						dialog.cancel();
					}
					
				});
				
				Button cancelbutton = (Button) dialog.findViewById(R.id.loginpromptcancel);
				cancelbutton.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View v) {
						dialog.cancel();
					}
					
				});
				
				Button submitbutton = (Button) dialog.findViewById(R.id.loginpromptsubmit);
				submitbutton.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View arg0) {
						EditText et = (EditText) dialog.findViewById(R.id.loginpromptemailaddress);
						String emailadd = et.getText().toString();
						et = (EditText) dialog.findViewById(R.id.loginpromptpassword);
						String password = et.getText().toString();
						
						user u = currentuserdetail.temporaryUserLookup(emailadd, password);
						if(u != null){
							//Change back the menu user
							if(u.getUserImage().length() > 0){
								LinearLayout ll = (LinearLayout)menu.this.findViewById(R.id.menuuserlayer);
								ll.setVisibility(View.VISIBLE);
								
								ImageView iv = (ImageView)menu.this.findViewById(R.id.menuCustomerImage);
								Bitmap bm = imageHelper.getImageFromResource(menu.this, u.getUserImage());
								iv.setImageBitmap(bm);
							}
							
							TextView tv = (TextView)menu.this.findViewById(R.id.menuCustomerWelcomeText);
							tv.setText("Welcome "+emailadd);
							
							currentuserdetail.currentuser = u;
							Toast.makeText(_self, "Welcome "+emailadd+" ! You can now start ordering foods.", Toast.LENGTH_SHORT).show();
						}
						else{
							Toast.makeText(_self, "Failed to login. Please check your email address/password.", Toast.LENGTH_SHORT).show();
						}
						dialog.cancel();
					}
					
				});
				
				dialog.show();
			}
			
		});
		
		Button menuserveme = (Button)findViewById(R.id.menuserveme);
		menuserveme.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				Toast.makeText(_self, "You will be attended shortly! :) ", Toast.LENGTH_LONG).show();
			}
			
		});
		
		Button logout = (Button)findViewById(R.id.menulogout);
		logout.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				
				String alertMsg = "Are you sure you would like to logout, your unplaced order will be lost";
				AlertDialog.Builder builder = new AlertDialog.Builder(_self);
				builder.setTitle("Exit confirmation!").setMessage(alertMsg)
				       .setCancelable(true)
				       .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {

						@Override
						public void onClick(DialogInterface arg0, int arg1) {
							arg0.cancel();
						}
				    	   
				       })
				       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
				           @Override
						public void onClick(DialogInterface dialog, int id) {
				        	   // TODO Auto-generated method stub
								currentcartitems.cartitems.removeAllElements();
								
								Intent i = new Intent(_self,login.class);
								_self.startActivity(i);
								
								_self.finish();
				           }
				       });
				AlertDialog alert = builder.create();
				alert.show();
			}
			
		});
		
		Button menubill = (Button)findViewById(R.id.menubill);
		menubill.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				if(currentcartitems.totalCartPrice() > 0){
					String alertMsg = "The bill will be send to you shortly with the total amount of MYR " + String.valueOf(currentcartitems.totalCartPrice());
					AlertDialog.Builder builder = new AlertDialog.Builder(_self);
					builder.setTitle("Bill")
							.setMessage(alertMsg)
					       .setCancelable(false)
					       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					           @Override
							public void onClick(DialogInterface dialog, int id) {
					              dialog.cancel();  
					           }
					       });
					AlertDialog alert = builder.create();
					alert.show();
				}
				else{
					Toast.makeText(_self, "You have not order anything.", Toast.LENGTH_LONG).show();
				}
			}
			
		});
		
		Vector<mMenuItem> menuItems = new Vector<mMenuItem>();
		
		mMenuItem menuitem = new mMenuItem();
		menuitem.setMenuname("Menu");
		menuitem.setImage("mainmenu/foodmenu.png");
		menuitem.setActivity(samplegridview.class);
		menuItems.add(menuitem);
		
		menuitem = new mMenuItem();
		menuitem.setMenuname("Cart");
		menuitem.setImage("mainmenu/shop.png");
		menuitem.setActivity(cart.class);
		menuItems.add(menuitem);
		
		menuitem = new mMenuItem();
		menuitem.setMenuname("What's New");
		menuitem.setImage("mainmenu/new_icon.png");
		menuitem.setActivity(whatsnew.class);
		menuItems.add(menuitem);
		
		menuitem = new mMenuItem();
		menuitem.setMenuname("Promotion");
		menuitem.setImage("mainmenu/promotion.png");
		menuitem.setActivity(productdiscount.class);
		menuItems.add(menuitem);
		
		menuitem = new mMenuItem();
		menuitem.setMenuname("Favourite");
		menuitem.setImage("mainmenu/favourite.png");
		menuitem.setActivity(cart.class);
		menuItems.add(menuitem);
		
		menuitem = new mMenuItem();
		menuitem.setMenuname("Feedback");
		menuitem.setImage("mainmenu/feedback.png");
		menuitem.setActivity(cart.class);
		menuItems.add(menuitem);
		
		menuitem = new mMenuItem();
		menuitem.setMenuname("Interact");
		menuitem.setImage("mainmenu/interact.png");
		menuitem.setActivity(cart.class);
		menuItems.add(menuitem);
		
		GridView menuview = (GridView)findViewById(R.id.menuview);
		menuview.setAdapter(new menuAdapter(this,menuItems));
	}
	
	public void exitConfirmation(){
		AlertDialog.Builder ab = new AlertDialog.Builder(this);
		ab.setTitle("Exit Confirmation");
		ab.setPositiveButton("Ok",new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				finish();
			}
			
		});
		ab.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){

			@Override
			public void onClick(DialogInterface arg0, int arg1) {
				
			}
			
		});
		ab.create().show();
	}
	
	public class menuAdapter extends BaseAdapter{
		
		Context mContext;
		Vector<mMenuItem> mMenuItems;

		public menuAdapter(Context mContext,Vector<mMenuItem> mMenuItems){
			this.mContext = mContext;
			this.mMenuItems = mMenuItems;
		}
		
		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return this.mMenuItems.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return this.mMenuItems.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			final mMenuItem mi = mMenuItems.get(position);
        	
            LinearLayout menuItemView = null;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
            	LayoutInflater li = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            	menuItemView = (LinearLayout) li.inflate(R.layout.menuitem, null);
            } else {
            	menuItemView = (LinearLayout) convertView;
            }

            BufferedInputStream buf;
			try {
				
				//Set Image
				ImageView iv = (ImageView)menuItemView.findViewById(R.id.menuitemimage);
				buf = new BufferedInputStream(_assetManager.open(mi.getImage()));
				Bitmap bitmap = BitmapFactory.decodeStream(buf);
				iv.setImageBitmap(bitmap);
				iv.setScaleType(ScaleType.FIT_XY);
				
				//Set Menu Item Name
				TextView tv = (TextView)menuItemView.findViewById(R.id.menuitemname);
				tv.setText(mi.getMenuname());
				
				menuItemView.setOnClickListener(new OnClickListener(){

					@Override
					public void onClick(View arg0) {
						
						Intent i = new Intent(mContext,mi.getActivity());
						if(mi.getMenuname().equals("Menu")){
							i.putExtra("categoryid", "0");
							i.putExtra("isroot", "true");
							_self.startActivityForResult(i, menu.requestCode);
						}
						else{
							_self.startActivity(i);
						}
					}		
				});
				
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
            
            return menuItemView;
		}
		
	}
	
	public class mMenuItem{
		public Class<?> getActivity() {
			return activity;
		}
		public void setActivity(Class<?> activity) {
			this.activity = activity;
		}
		public String getMenuname() {
			return menuname;
		}
		public void setMenuname(String menuname) {
			this.menuname = menuname;
		}
		public String getImage() {
			return image;
		}
		public void setImage(String image) {
			this.image = image;
		}
		Class<?> activity;
		String menuname;
		String image;
	}
}
